package com.frxuexi.mymvi

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.frxuexi.lib_base.http.ApiService
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class MviViewModel @Inject constructor(val apiService: ApiService):ViewModel(){
    val mviChannel = Channel<MviIntent>()

    private var _mviState= MutableStateFlow<MviState>(MviState.onLoading)
    val mviState:StateFlow<MviState>
        get() = _mviState

    init {
        viewModelScope.launch {
            mviChannel.receiveAsFlow().collect{
                when(it){
                    is MviIntent.getNews->{
                        getNews()
                    }
                }
            }
        }
    }

    fun getNews(){
        viewModelScope.launch {
            apiService.getNews().flowOn(Dispatchers.IO)
                .catch {
                    Log.i("lr",it.message.toString())
                }.collect{
                    if(it.code==200){
                        _mviState.value=MviState.onSuccess(it.data)
                    }else{
                        _mviState.value=MviState.onError(it.message)
                    }
                }
        }
    }
}